package com.lkd.handler;

import com.alibaba.fastjson.JSON;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class RepearHandler implements MsgHandler {
    @Autowired
    private TaskService taskService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        List<StatusInfo> statusInfo = vmStatusContract.getStatusInfo();
        List<String> list = new ArrayList<>();
        boolean flag = true;
        for (StatusInfo info : statusInfo) {
            //有设备部件损坏信息
            if(!info.isStatus()){
                flag = false;
                list.add(info.getStatusCode());
            }
        }
        if(flag == false){
            //获取工单创建封装类
            TaskViewModel taskViewModel = getTaskViewModel(vmStatusContract, list);
            taskService.createTask(taskViewModel);
        }
    }

    private TaskViewModel getTaskViewModel(VmStatusContract vmStatusContract, List<String> list) {
        TaskViewModel taskViewModel = new TaskViewModel();
        taskViewModel.setCreateType(0);
        String innerCode = vmStatusContract.getInnerCode();
        taskViewModel.setInnerCode(innerCode);
        taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);
        taskViewModel.setDesc("以下部件已损坏:"+ JSON.toJSONString(list));
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        VmVO vmInfo = vmService.getVMInfo(innerCode);
        Long regionId = vmInfo.getRegionId();
        String roleCode = VMSystem.USER_REPAIRER;
        String key = "taskNumSet."+date+regionId+roleCode;
        Set range = redisTemplate.opsForZSet().range(key, 0, 1);
        List collect = (List) range.stream().collect(Collectors.toList());
        Integer userId = (Integer) collect.get(0);
        taskViewModel.setUserId(userId);
        return taskViewModel;
    }
}
